package model

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"pipline_build_tag/conf"
	"pipline_build_tag/utils"
	"time"
)

// 标签存储表
type DockerTag struct {
	*gorm.Model
	Id            int64
	Name          string `gorm:"type:varchar(255);COMMENT:项目名称"`
	NodeName      string `gorm:"type:varchar(255);COMMENT:节点名称"`
	Tag           string `gorm:"type:varchar(255);COMMENT:镜像TAG"`
	DateTag       string `gorm:"type:varchar(50);COMMENT:TAG时间"`
	CommitMessage string `gorm:"type:varchar(255);COMMENT:git分支commit信息"`
}

var DB *gorm.DB
var logw = utils.WriteLog()

func Init() {
	var dsn = conf.Server.MysqlConfig.USER + ":" + conf.Server.MysqlConfig.PASSWORD + "@tcp(" + conf.Server.MysqlConfig.ADDRESS + ")/" + conf.Server.MysqlConfig.DBNAME + "?charset=utf8mb4&parseTime=true&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.New(
			//将标准输出作为Writer
			log.New(os.Stdout, "\r\n", log.LstdFlags),
			logger.Config{
				//设定慢查询时间阈值为500 Second
				SlowThreshold: 500 * time.Second,
				//设置日志级别，只有Warn和Info级别会输出慢查询日志
				//LogLevel: logger.Info,
				LogLevel: logger.Error,
				Colorful: false,
			}),
	})
	if err != nil {
		logw.Println("数据库连接失败", err)

		os.Exit(1)
	}
	DB = db

	err = DB.AutoMigrate(&DockerTag{})
	if err != nil {
		logw.Println("数据表创建错误", err)
		os.Exit(2)
	}
}
